package httpCtrler

import (
	st "kjjcgroup_server/model"
	sv "kjjcgroup_server/service"
	"kjjcgroup_server/units"
	"net/http"
	"os"
	"strconv"

	jwt "github.com/appleboy/gin-jwt"
	"github.com/gin-gonic/gin"
	"github.com/go-xorm/xorm"
)

type MsgReturn struct {
	Msg  string      `json:"Msg"`
	Data interface{} `json:"Data"`
}
type MsgReturn1 struct {
	UserInfo   interface{} `json:"UserInfo"`
	AuthNumber int         `json:"AuthNumber"`
	UserNumber int         `json:"UserNumber"`
}
type PageRtnData struct {
	PageCount int `json:"PageCount"`
	PageIdx   int `json:"PageIdx"`
	DataCount int `json:"DataCount"`
}

func init() {
	if err := os.Mkdir("./upload", os.ModeDir); err != nil {
		if !os.IsExist(err) {
			panic(err)
		}
	}
}

func Page(c *gin.Context) (current, pageSize int) {
	PageIdx := c.Query("current")
	PageCnt := c.Query("pageSize")
	current = -1
	pageSize = -1
	if len(PageIdx) > 0 {
		current, _ = strconv.Atoi(PageIdx)
	}
	if len(PageCnt) > 0 {
		pageSize, _ = strconv.Atoi(PageCnt)
	}
	return
}

func rtnData(count int64, pageCnt, pageIdx int, collArr interface{}) (rtnDt interface{}) {
	rtnDt = &struct {
		PageRtnData
		Data interface{}
	}{Data: collArr, PageRtnData: PageRtnData{PageCount: pageCnt, PageIdx: pageIdx, DataCount: int(count)}}
	// fmt.Println("count:", count, "PageIdx", pageIdx)
	return
}

func StartRouter(router *gin.Engine, routerAuth *gin.RouterGroup) {
	router.GET("/", func(context *gin.Context) {
		context.String(http.StatusOK, "后端已启动")
	})

	router.GET("/getIp", func(c *gin.Context) {
		ip := c.ClientIP()
		c.String(http.StatusOK, ip)
	})
	router.GET("/getPassW", func(c *gin.Context) {
		str := c.Query("str")
		c.JSON(http.StatusOK, &MsgReturn{Msg: http.StatusText(http.StatusOK), Data: units.TokenDecrypt(str)})
	})

	routerAuth.GET("/myLogger", MyLogger)
	LogMap["/myLogger"] = "日志管理"

	router.GET("/base64", func(c *gin.Context) {
		str := c.Query("str")
		obj := c.Query("obj")
		if str != "" {
			c.JSON(http.StatusOK, &MsgReturn{Msg: http.StatusText(http.StatusOK), Data: units.Base64ToJson(str)})
		}
		if obj != "" {
			c.JSON(http.StatusOK, &MsgReturn{Msg: http.StatusText(http.StatusOK), Data: units.JsonToBase64(obj)})
		}
	})

}

func CheckMysqlError(c *gin.Context, err error) {
	if err != nil {
		c.JSON(http.StatusConflict, &MsgReturn{Msg: "Open DataBase Failed", Data: nil})
		return
	}
}

func DeferMysql(mysql *xorm.Engine) {
	err := mysql.Close()
	if err != nil {
		return
	}
}

func IsAuth(c *gin.Context) {
	clm := jwt.ExtractClaims(c)
	perm := clm[SessPermissionId]
	if perm != "9" {
		c.JSON(409, &MsgReturn{Msg: "无权限", Data: nil})
		return
	}
}
func CurrentAccount(c *gin.Context) string {
	clm := jwt.ExtractClaims(c)
	return clm[SessUserAccount].(string)
}
func CurrentUserId(c *gin.Context) int {
	clm := jwt.ExtractClaims(c)
	userId, _ := strconv.Atoi(clm[SessUserId].(string))
	return userId
}

func isShowSQL() bool {
	return true
}

func LoginNumAdd(UserAccount string) {
	mysql, err := sv.GetEngine()
	units.CheckError(err)
	defer DeferMysql(mysql)
	mysql.ShowSQL(isShowSQL())
	sess := mysql.NewSession()
	defer sess.Close()
	var collArr []*st.ModAddSysUser
	err = mysql.Where("user_account=?", UserAccount).Find(&collArr)
	_, errU := mysql.Where("user_account=?", UserAccount).Update(&st.ModAddSysUser{LoginNum: collArr[0].LoginNum + 1})
	if errU != nil {
		return
	}
	if err != nil {
		err := sess.Rollback()
		if err != nil {
			return
		}
	} else {
		err = sess.Commit()
	}
}
